package com.ctrip.ec.api.mobile.controller;

import com.ctrip.ec.api.mobile.aop.AuthLogin;
import com.ctrip.ec.api.mobile.common.PagerInfo;
import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;
import com.ctrip.ec.api.mobile.model.order.OrderModel;

import com.ctrip.ec.biz.dao.goods.GoodsSpecDao;
import com.ctrip.ec.biz.dao.order.OrderDao;
import com.ctrip.ec.biz.dao.order.OrderDiscountDao;
import com.ctrip.ec.biz.dao.order.OrderGoodsDao;
import com.ctrip.ec.biz.dao.payment.PaymentDao;
import com.ctrip.ec.biz.dao.shipping.ShippingConfigDao;
import com.ctrip.ec.biz.dao.store.StoreDao;
import com.ctrip.ec.biz.entity.goods.GoodsSpecEntity;
import com.ctrip.ec.biz.entity.order.*;
import com.ctrip.ec.biz.entity.payment.PaymentEntity;
import com.ctrip.ec.biz.entity.payment.PaymentStatus;
import com.ctrip.ec.biz.entity.shipping.ShippingConfigEntity;
import com.ctrip.ec.biz.entity.store.StoreEntity;
import com.ctrip.ec.biz.kuaidi.HttpRequest;
import com.ctrip.ec.biz.kuaidi.MD5;
import com.ctrip.ec.dal.PagerSetting;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.commons.collections.map.AbstractReferenceMap;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by jiangzy on 2018/9/3.
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderDao order;

    @Autowired
    private StoreDao store;

    @Autowired
    private PaymentDao payment;

    @Autowired
    private OrderGoodsDao orderGoods;

    @Autowired
    private GoodsSpecDao goodsSpec;

    @Autowired
    private ShippingConfigDao shippingConfig;


    @Value("${imageDomain}")
    private String imageDomain;

    @AuthLogin
    @PostMapping("cancel")
    public void cancel(@RequestBody List<Long> ids) throws SQLException {
        if (ids != null && ids.size() > 0) {
            List<OrderEntity> orderList = order.listByIds(ids);
            order.cancel(orderList);
        }
    }

    @GetMapping("list")
    @AuthLogin
    public List<OrderModel> list(@RequestParam(required = false) Integer status,
                                 @RequestParam(required = false) Integer pageIndex,
                                 @RequestParam(required = false) Integer pageSize) throws SQLException {
        String where = "member_id=" + RequestContext.getMemberId();
        if (status != null) {
            where += " and order_status=" + status;
        }
        PagerSetting setting = new PagerSetting();
        setting.setWhere(where);
        if (pageIndex != null) {
            setting.setPageIndex(pageIndex);
        }
        if (pageSize != null) {
            setting.setPageSize(pageSize);
        }
        List<OrderEntity> list = order.list(setting);
        List<StoreEntity> storeList = store.listByIds(list.stream().map(t -> t.getStoreId()).distinct().collect(Collectors.toList()));

        List<OrderModel> models = new ArrayList<>();
        for (OrderEntity entity : list) {
            OrderModel model = new OrderModel(entity);
            Optional<StoreEntity> storeEntity = storeList.stream().filter(t -> t.getId().equals(entity.getStoreId())).findFirst();
            if (storeEntity.isPresent()) {
                StoreEntity tmp = storeEntity.get();
                model.setStoreName(tmp.getName());
                model.setStoreLogoImageUrl(this.imageDomain + tmp.getLogoImageUrl());
            }

            model.setGoodsList(orderGoods.listByOrderId(entity.getId()));

            int goodsCount = 0;
            for (OrderGoodsEntity goodsEntity : model.getGoodsList()) {
                goodsCount += goodsEntity.getBuyNum();
                goodsEntity.setGoodsImage(this.imageDomain + goodsEntity.getGoodsImage());
            }
            model.setBuyCount(goodsCount);
            models.add(model);
        }

        RequestContext.setResponseHeaderPager(new PagerInfo(setting.getRecordCount(), setting.getPageIndex(), setting.getPageSize()));
        return models;
    }


    @GetMapping("detail")
    @AuthLogin
    public OrderModel detail(@RequestParam Long id) throws SQLException {
        OrderEntity entity = order.entity(id);
        if (!entity.getMemberId().equals(RequestContext.getMemberId())) {
            throw new ValidateException("非法操作");
        }
        PaymentEntity paymentEntity = payment.entity(entity.getPaymentId());

        StoreEntity storeEntity = store.entity(entity.getStoreId());

        OrderModel model = new OrderModel(entity);
        model.setPaymentName(paymentEntity.getName());

        if (storeEntity != null) {
            model.setStoreName(storeEntity.getName());
            model.setStoreLogoImageUrl(this.imageDomain + storeEntity.getLogoImageUrl());
        }

        List<OrderGoodsEntity> goodsList = orderGoods.listByOrderId(entity.getId());
        model.setGoodsList(goodsList);

        int goodsCount = 0;
        for (OrderGoodsEntity goodsEntity : model.getGoodsList()) {
            goodsCount += goodsEntity.getBuyNum();
            goodsEntity.setGoodsImage(this.imageDomain + goodsEntity.getGoodsImage());
        }
        model.setBuyCount(goodsCount);

        return model;
    }


    @GetMapping("logistics")
    public Map<String, String> logistics(@RequestParam Long orderId) throws SQLException {
        OrderEntity entity = order.entity(orderId);
        Map<String, String> map = new HashMap<>();
        map.put("shippingCode", entity.getShippingCode());
        map.put("shippingName", entity.getShippingName());
        return map;
    }

    @GetMapping("statusSum")
    @AuthLogin
    public Map<String, Long> statusSum() throws SQLException {
        Long memberId = RequestContext.getMemberId();
        List<StatusSumModel> list = this.order.statusSum(memberId);
        Map<String, Long> map = new HashMap<>();
        Long count = 0L;
        Optional<StatusSumModel> statusSumModelOptional = list.stream().filter(t -> t.getOrderStatus().equals(OrderStatus.待支付.getId())).findFirst();
        if (statusSumModelOptional.isPresent()) {
            count = statusSumModelOptional.get().getCount();
        }
        map.put("toPay", count);

        statusSumModelOptional = list.stream().filter(t -> t.getOrderStatus().equals(OrderStatus.待发货.getId())).findFirst();
        if (statusSumModelOptional.isPresent()) {
            count = statusSumModelOptional.get().getCount();
        } else {
            count = 0L;
        }
        map.put("toDeliver", count);

        statusSumModelOptional = list.stream().filter(t -> t.getOrderStatus().equals(OrderStatus.已发货.getId())).findFirst();
        if (statusSumModelOptional.isPresent()) {
            count = statusSumModelOptional.get().getCount();
        } else {
            count = 0L;
        }
        map.put("hasDeliver", count);

        return map;
    }

    @GetMapping("shipping")
    public List<Map<String, String>> shipping(@RequestParam Long orderId) throws Exception {
        OrderEntity entity = this.order.entity(orderId);
        ShippingConfigEntity shippingConfigEntity = shippingConfig.entityByName(entity.getShippingName());
        if (shippingConfigEntity == null) {
            throw new ValidateException(entity.getShippingName() + "-物流公司没有配置");
        }
        List<Map<String, String>> list = new ArrayList<>();
        String com = shippingConfigEntity.getCode();
        String num = entity.getShippingCode();
        String param = "{\"com\":\"" + com + "\",\"num\":\"" + num + "\"}";
        String customer = "31E362AEA4850A8B617BC68CA5FB155E";
        String key = "ghRXfeuU5067";
        String sign = MD5.encode(param + key + customer);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("param", param);
        params.put("sign", sign);
        params.put("customer", customer);
        String resp = new HttpRequest().postData("http://poll.kuaidi100.com/poll/query.do", params, "utf-8").toString();
        JsonObject jsonObject = new JsonParser().parse(resp).getAsJsonObject();
        String message = jsonObject.get("message").getAsString();
        JsonArray array = jsonObject.getAsJsonArray("data");
        if (!message.equals("ok") && array == null) {
            throw new ValidateException(message);
        }
        for (int i = 0; i < array.size(); i++) {
            JsonElement element = array.get(i);
            Map<String, String> map = new HashMap<>();
            map.put("time", element.getAsJsonObject().get("ftime").getAsString());
            map.put("context", element.getAsJsonObject().get("context").getAsString());
            list.add(map);
        }

        return list;
    }
}
